// 商品分类管理1
"use strict";
const Service = require("egg").Service;
const { Op } = require("sequelize");

const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
const await = require("await-stream-ready/lib/await");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sClasses extends Service {
  // pc
  // 全查【all】--针对商品查询
  async pc_s_queryAll() {
    // 查询所有商品分类，并且根据分类查询分类下的商品以及文件
    let response = null;
    const { ctx } = this;
    try {
      // 查询所有商品分类
      const OneOfClasses = await ctx.model.Classes.findAll({
        where: {
          cid: 0
        },
        order: [["sort", "DESC"]]
      });
      let promises = OneOfClasses?.map(async item => {  
        let _item = JSON.parse(JSON.stringify(item));  
        _item.children = await ctx.model.Classes.findAll({ where: { cid: item?.id ?? "" } });  
        return _item;  
      }); 
      // 使用 Promise.all 等待所有异步操作完成  
      const result = await Promise.all(promises).catch(() => {});
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 200 });
      response = successRes(result);
    } catch (error) {
      console.error(error, '<---- error - wa 商品分类查询');
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }
    // 全查【all】--针对分类查询
    async pc_s_queryClassAll() {
      // 查询所有商品分类，并且根据分类查询分类下的商品以及文件
      let response = null;
      const { ctx } = this;
      try {
        // 查询所有商品分类
        const result = await ctx.model.Classes.findAll({
          where: {
            cid: 0
          },
          order: [["sort", "DESC"]]
        });
        await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 200 });
        response = successRes(result);
      } catch (error) {
        console.error(error, '<---- error - wa 商品分类查询');
        await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 401 });
        response = failRes(401);
      }
      return response;
    }
  // 查
  async pc_s_query(params) {
    let response = null;
    const { ctx } = this;
    try {
      let title = params?.title ?? "";
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const result = await ctx.model.Classes.findAndCountAll({
        where: {
          title: {
            [Op.like]: `%${title}%`, // 使用 Op.like 实现模糊匹配
          },
        },
        order: [["createdAt", "DESC"]], // 排序-降序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });
      await Journal(ctx, { operatorType: "商品分类 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: result?.count ?? 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 商品分类查询");
      await Journal(ctx, { operatorType: "商品分类 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 增加分类 - 后台管理
  async pc_s_create(params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Classes.create(
        params,
        { attributes: { extends: ["id", "title", "cid", "img", "sort"] } } // 向数据库插入特定字段
      );
      await Journal(ctx, { operatorType: "商品分类 -> 新增", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 商品分类新增");
      await Journal(ctx, { operatorType: "商品分类 -> 新增", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 更新分类 - 后台管理
  async pc_s_update(params) {
    let response = null;
    const { ctx } = this;
    try {
      console.log(params, "<---- params - 商品分类更新");
      // if(params.sort === null || params.sort === undefined || params.sort === ""){
      //   params.sort = null;
      //   console.log(params.sort, "<---- params.sort - 商品分类更新");
      // }
      // const classes = await ctx.model.Classes.findByPk(params?.id);
      // console.log('classes类别id: ', classes);
      const upClasses =  await ctx.model.Classes.update(params, {
        where: { 
          id: params?.id ?? "",

         },
        // if(params.sort ){
        //   params.sort = parseInt(params?.sort)
        // }
       attributes: { extends: ["id", "title", "cid", "img", "sort"] },
      });
      console.log(upClasses, "<---- upClasses - 商品分类更新");

      await Journal(ctx, { operatorType: "商品分类 -> 编辑", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 商品分类编辑");
      await Journal(ctx, { operatorType: "商品分类 -> 编辑", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删除分类 - 后台管理
  async pc_s_delete(params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Classes.destroy({
        where: { id: params?.id ?? "" },
      });
      await Journal(ctx, { operatorType: "商品分类 -> 删除", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 商品分类删除");
      await Journal(ctx, { operatorType: "商品分类 -> 删除", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 商品分类 -> 查询(不分页)
  async pc_s_query_all() {
    let response = null;
    const { ctx } = this;
    try {
      const result = await ctx.model.Classes.findAll({
        order: [["updatedAt", "DESC"]], // 排序
      });
      await Journal(ctx, {
        operatorType: "商品分类 -> 查询(不分页)",
        code: 200,
      });
      response = successRes(result);
    } catch (error) {
      console.error(error, "<---- error - 商品分类查询(不分页)");
      await Journal(ctx, {
        operatorType: "商品分类 -> 查询(不分页)",
        code: 401,
      });
      response = failRes(401);
    }
    return response;
  }

  // wa
  // 查询所有商品分类
  async wa_s_query() {
    // 查询所有商品分类，并且根据分类查询分类下的商品以及文件
    let response = null;
    const { ctx } = this;
    try {
      // 查询所有商品分类
      const fdatas = await ctx.model.Classes.findAll({
        where: { cid: 0 },
        order: [["sort", "DESC"]]
      });
      const rdatas = await ctx.model.Classes.findAll({
        where: {
          cid: {
            [Op.ne]: null,
          }
        },
        order: [["sort", "DESC"]]
      });
      const result = { fdatas, rdatas }
      // let promises = OneOfClasses?.map(async item => {  
      //   let _item = JSON.parse(JSON.stringify(item));  
      //   _item.children = await ctx.model.Classes.findAll({ where: { cid: item?.id ?? "" } });  
      //   return _item;  
      // }); 
      // 使用 Promise.all 等待所有异步操作完成  
      // const result = await Promise.all(promises).catch(() => {});
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 200 });
      response = successRes(result);
    } catch (error) {
      console.error(error, '<---- error - wa 商品分类查询');
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  //依据二级分类查询商品
  async wa_s_second_class_goods(params) {
    console.log(params,"<=============== //依据二级分类查询商品")
    let response = null;
    let result = "";
    let count = "";
    const { ctx } = this;
    try {
      result = await ctx.model.ProductsClasses.findAll({
        where: {
          cid: params.cid
        },
        attributes: ['id', 'pid'], 
      });
      count = await ctx.model.Products.count({
        where: {
          id: result.map(item => item.pid)
        }
      });
      response =await ctx.model.Products.findAll({
        where:{
          id: result.map(item => item.pid)
        }
      });

      await Journal(ctx, { operatorType: '二级分类商品 -> 查询', code: 200 });
      response = successRes({
        response,
        total: count || 0,
      });

    }catch (error) {
      console.error(error, '<---- error - wa 二级分类商品');
      await Journal(ctx, { operatorType: '二级分类商品 -> 查询', code: 401 });
      response = failRes(401);

    }
    return response;
  }


}

module.exports = sClasses;
